from fastapi import APIRouter, Body
from intelli_port.data_layer.clients import mysql_execute_read, mysql_execute_write


router = APIRouter()


@router.get("/list")
async def list_params():
    rows = mysql_execute_read("SELECT `key`, `value`, COALESCE(updated_at, NOW()) FROM kv_config", fetch="all").get("rows", [])
    return {"items": [{"key": r[0], "value": r[1], "updated_at": str(r[2])} for r in rows]}


@router.post("/set")
async def set_param(payload: dict = Body(...)):
    k = str(payload.get("key") or "").strip()
    v = str(payload.get("value") or "")
    if not k:
        return {"ok": False}
    mysql_execute_write("INSERT INTO kv_config(`key`,`value`,updated_at) VALUES(%s,%s,NOW()) ON DUPLICATE KEY UPDATE `value`=VALUES(`value`), updated_at=VALUES(updated_at)", (k, v))
    return {"ok": True}


@router.post("/rollback")
async def rollback(payload: dict = Body(...)):
    items = payload.get("items") or []
    for it in items:
        k = str(it.get("key") or "").strip()
        v = str(it.get("value") or "")
        if not k:
            continue
        mysql_execute_write("INSERT INTO kv_config(`key`,`value`,updated_at) VALUES(%s,%s,NOW()) ON DUPLICATE KEY UPDATE `value`=VALUES(`value`), updated_at=VALUES(updated_at)", (k, v))
    return {"ok": True, "count": len(items)}